using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace MiniAspNetCore
{
    /// <summary>
    /// http监听服务
    /// </summary>
    public class HttpListenerServer : IServer
    {
        /// <summary>
        /// http监听实例
        /// </summary>
        private readonly HttpListener _httpListener;
        /// <summary>
        /// http监听地址
        /// </summary>
        private readonly string[] _urls;

        /// <summary>
        /// 初始化http监听服务
        /// </summary>
        /// <param name="urls">http监听地址</param>
        public HttpListenerServer(params string[] urls)
        {
            _httpListener = new HttpListener();
            _urls = urls.Length > 0 ? urls : new[] { "http://localhost:5000/" };
        }

        /// <summary>
        /// 开启服务
        /// </summary>
        /// <param name="handler">请求处理管道</param>
        public async Task StartAsync(RequestDelegate handler)
        {
            // 配置并启动http监听
            Array.ForEach(_urls, url => _httpListener.Prefixes.Add(url));
            _httpListener.Start();

            // 循环监听并处理请求
            while (true)
            {
                HttpListenerContext listenerContext = await _httpListener.GetContextAsync(); // 异步监听并获取原始上下文
                HttpListenerFeature feature = new HttpListenerFeature(listenerContext); // 使用原始上下文构建http处理程序
                IFeatureCollection features = new FeatureCollection() // 初始化处理程序集合,并注册http处理程序
                    .Set<IHttpRequestFeature>(feature)
                    .Set<IHttpResponseFeature>(feature);
                HttpContext httpContext = new HttpContext(features); // 使用处理程序集合初始化http上下文
                await handler(httpContext); // 使用请求管道处理http请求
                listenerContext.Response.Close(); // 应用响应
            }
        }
    }
}
